package com.gjy.redis.controller;

import com.gjy.redis.domain.AjaxResult;
import com.gjy.redis.domain.vo.ScriptRequest;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RScript;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-07-20 10:27:45
 */
@RestController
@Slf4j
@RequestMapping("/script")
public class ScriptController {
    @Resource
    private Redisson redisson1;
    @Resource
    private Jedis jedis;

    @PostMapping("/redisson")
    public AjaxResult redisson(@RequestParam String script) {
        RScript rs = redisson1.getScript();
        String s = rs.scriptLoad(script);
        log.info("s = {}", s);
        return AjaxResult.builder().data(s).build();
    }

    @PostMapping("/redisson1")
    public AjaxResult redisson1(@RequestBody ScriptRequest request) {
        Object o;
        RScript script = redisson1.getScript();
        if (!"".equals(request.getScript())) {
            String s = script.scriptLoad(request.getScript());
            List<Object> keys = Lists.newArrayList(request.getKeys());
            List<Object> values = Lists.newArrayList(request.getValues());
            o = script.evalSha(RScript.Mode.READ_WRITE, s, RScript.ReturnType.VALUE, keys, values.toArray());
        } else {
            List<Object> keys = Lists.newArrayList(request.getKeys());
            List<Object> values = Lists.newArrayList(request.getValues());
            o = script.evalSha(RScript.Mode.READ_WRITE, request.getScript(), RScript.ReturnType.VALUE, keys, values.toArray());
        }
        log.info("o = {}, type = {}", o, o.getClass());
        return AjaxResult.builder().data(o).build();
    }

    @PostMapping("/jedis")
    public AjaxResult jedis(@RequestParam String script) {
        String s = jedis.scriptLoad(script);
        log.info("s = {}", s);
        return AjaxResult.builder().data(s).build();
    }

    @PostMapping("/jedis1")
    public AjaxResult jedis1(@RequestBody ScriptRequest request) {
        Object o;
        if ("".equals(request.getScript())) {
            o = jedis.evalsha(request.getSha(), request.getKeys(), request.getValues());
        } else {
            String s = jedis.scriptLoad(request.getScript());
            o = jedis.evalsha(s, request.getKeys(), request.getValues());
        }
        log.info("o = {}, type = {}", o, o.getClass());
        return AjaxResult.builder().data(o).build();
    }

    @PostMapping("/hello")
    public AjaxResult hello() {
        return AjaxResult.builder().data("Hello Redis").build();
    }
}
